//
//  GWHomeViewController.m
//  新浪微博
//
//  Created by qianfeng on 16/1/9.
//  Copyright (c) 2016年 高炜. All rights reserved.
//

#import "GWHomeViewController.h"
#import "GWMyBarButtonItem.h"
#import "GWtestView.h"
#import "GWMyHomeBtn.h"
#import "GWPopMenu.h"
#import "GWAccountTool.h"
#import "GWAccount.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "GWFootView.h"
#import "GWStatuseTool.h"
#import "GWUserInfoTool.h"
#import "GWStatuseCell.h"
#import "GWStatuseFrame.h"
#import "GWLink.h"
#import "GWDetailStatuseTableViewController.h"
@interface GWHomeViewController ()<GWPopMenuDelegate>
@property (nonatomic,copy)NSMutableArray *statuseFormes;
@property (nonatomic,weak)UIRefreshControl *refresh;
@property (nonatomic,weak)GWFootView *footerView;

@property (nonatomic,weak)GWMyHomeBtn *btn;
@end

@implementation GWHomeViewController
-(NSMutableArray *)statuseFormes
{
    if (_statuseFormes ==nil) {
        _statuseFormes =[NSMutableArray array];
    }
    return _statuseFormes;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavgation];
    
    [self setRefreshControl];
    
    
    [self setUserInfo];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(linkDidSelected:) name:GWLinkDidSelectedNotification object:nil];
    self.tableView.backgroundColor =GWGlobalBackgroundColor;
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)linkDidSelected:(NSNotification *)note
{
    GWLink *link =note.userInfo[GWStatuseLink];
    if ([link.linkText hasPrefix:@"http"]) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:link.linkText]];
    }else
    {
        NSLog(@"非URL参数--%@",link.linkText);
    }
}
-(void)setUserInfo
{
    GWUserInfoParam *parameter =[GWUserInfoParam param];
    parameter.uid =[GWAccountTool Account].uid;
    [GWUserInfoTool userInfoWithParame:parameter success:^(GWUserInforResult *result) {
        
        [self.btn setTitle:result.name forState:UIControlStateNormal];
        
        GWAccount *account =[GWAccountTool Account];
        account.username =result.name;
        [GWAccountTool saveAccount:account];
    } failure:^(NSError *error) {
        
    }];
   
}
-(void)setRefreshControl
{
    UIRefreshControl *refresh =[[UIRefreshControl alloc]init];
    [self.view addSubview:refresh];
    [refresh addTarget:self action:@selector(refreshDidValueChange:) forControlEvents:UIControlEventValueChanged];
    [refresh beginRefreshing];
    self.refresh =refresh;
    [self refreshDidValueChange:refresh];
    
    GWFootView *footerView =[GWFootView footer];
    self.tableView.tableFooterView =footerView;
    self.footerView =footerView;
}
-(void)refreshDidValueChange:(UIRefreshControl *)refresh
{
    [self loadNewStatus:refresh];
}

-(NSArray*)statuseFormesWithStatuse:(NSArray *)statuses
{
    NSMutableArray  *frames =[NSMutableArray array];
    for (GWStatuseModel *statuse in statuses) {
        GWStatuseFrame *frame =[[GWStatuseFrame alloc]init];
        frame.statuse =statuse;
        [frames addObject:frame];
    }
    return frames;
}

-(void)loadNewStatus:(UIRefreshControl *)refresh
{
    /*
     
     since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
     max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
     count	false	int	单页返回的记录条数，最大不超过100，默认为20。
     page	false	int	返回结果的页码，默认为1。
     */
    GWHomeStatuseParameter *parameter=[GWHomeStatuseParameter param];
    GWStatuseFrame *frame =[self.statuseFormes firstObject];
    GWStatuseModel *status =frame.statuse;
    if (status) {
        parameter.since_id =status.idstr;
    }
    [GWStatuseTool homeStatuseWithParame:parameter success:^(GWHomeStastuseResult *respondObj) {
        NSArray *newStastus = [self statuseFormesWithStatuse:respondObj.statuses];
        NSIndexSet *indexSet =[[NSIndexSet alloc]initWithIndexesInRange:NSMakeRange(0, newStastus.count)];
        [self.statuseFormes insertObjects:newStastus atIndexes:indexSet];
        
        [self.tableView reloadData];
        
        [self.refresh endRefreshing];
        
        [self showNewStatusCount:newStastus.count];
    } failure:^(NSError *error) {
        [self.refresh endRefreshing];
    }];
}

-(void)loadMoreStatus
{
    GWHomeStatuseParameter *parameter=[GWHomeStatuseParameter param];
    GWStatuseFrame *frame =[self.statuseFormes lastObject];
    GWStatuseModel *lastStatus =frame.statuse;
    
    if (lastStatus) {
        parameter.max_id =[NSString stringWithFormat:@"%lld",[lastStatus.idstr longLongValue]-1];
    }
    [GWStatuseTool homeStatuseWithParame:parameter success:^(GWHomeStastuseResult *respondObj) {
        NSArray *newStastus = [self statuseFormesWithStatuse:respondObj.statuses];
        
        [self.statuseFormes addObjectsFromArray:newStastus];
        
        [self.tableView reloadData];
        
        [self.footerView endFresh];
    } failure:^(NSError *error) {
        [self.footerView endFresh];
    }];
    
    
}

-(void)showNewStatusCount:(NSInteger)count
{
    UILabel *label =[[UILabel alloc]init];
    if (count) {
        label.text =[NSString stringWithFormat:@"共有%ld条新的微博数据",count];
        [UIApplication sharedApplication].applicationIconBadgeNumber-=self.tabBarItem.badgeValue.integerValue;
        self.tabBarItem.badgeValue=nil;
    }
    else
    {
        label.text =@"没有新的微博数据";
    }
    label.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.textAlignment =NSTextAlignmentCenter;
    label.textColor =[UIColor whiteColor];
    
    label.frame =CGRectMake(0, 64-35, self.view.width, 35);
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    
    [UIView animateWithDuration:0.75 animations:^{
        label.transform =CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.75 delay:0.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            label.transform =CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}





-(void)setNavgation
{
    self.navigationItem.leftBarButtonItem =[GWMyBarButtonItem barButtonItemWithImageName:@"navigationbar_friendsearch" highLightName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(moreFriend)];
    self.navigationItem.rightBarButtonItem =[GWMyBarButtonItem barButtonItemWithImageName:@"navigationbar_pop" highLightName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    
    GWMyHomeBtn *btn =[[GWMyHomeBtn alloc]init];
    btn.height =35;
    [btn setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage reSizeWithName:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted];
    NSString *name =[GWAccountTool Account].username;
    [btn setTitle:name?name:@"首页"  forState:UIControlStateNormal];
    self.btn =btn;
    [btn addTarget:self action:@selector(navTitleOnTouch:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView =btn;
}
-(void)navTitleOnTouch:(GWMyHomeBtn *)btn
{

    [btn setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    GWPopMenu *popMenu =[[GWPopMenu alloc]init];
    popMenu.delegate =self;
    [popMenu show];
}
-(void)popMenuDidDismiss:(GWPopMenu *)menu
{
    UIButton *btn =(UIButton *)self.navigationItem.titleView;
    [btn setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}
-(void)moreFriend
{
    GWLog(@"moreFriend");
}
-(void)pop
{
    NSLog(@"%@",NSStringFromClass([self.tabBarController.tabBar class]));
    GWLog(@"pop");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.footerView.hidden= (self.statuseFormes.count==0);
    return self.statuseFormes.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GWStatuseCell *cell =[GWStatuseCell cellWithTableView:tableView];
    cell.statuseFrame =self.statuseFormes[indexPath.row];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GWStatuseFrame *statuse =self.statuseFormes[indexPath.row];
    return statuse.statuseCellHeight;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GWDetailStatuseTableViewController *vc =[[GWDetailStatuseTableViewController alloc]init];
    GWStatuseFrame *frame =self.statuseFormes[indexPath.row];
    vc.statuse =frame.statuse;
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.statuseFormes.count<=0||self.footerView.isRefreshing) return;
    CGFloat newHeight =scrollView.contentSize.height-scrollView.contentOffset.y;
    CGFloat sawFooterView =scrollView.height-self.tabBarController.tabBar.height;
    if (newHeight<(sawFooterView-20)) {
        [self.footerView beginFresh];
        
        [self loadMoreStatus];
        
    }
}

@end
